package cn.ccew.sys.web.manage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ccew.sys.model.SysResources;
import cn.ccew.sys.web.SysBaseController;

/**
 * s
 * 
 * @author lxj
 * 
 */
@Controller
public class MenuController extends SysBaseController {

	/**
	 * 
	 * @param rootMenuCode
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("loadmenu.wb")
	public void loadMenu(String rootMenuCode, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Criteria criteria = this.createCriteria(SysResources.class);

		if (StringUtils.isEmpty(rootMenuCode)) {
			criteria.add(Restrictions.isEmpty("parent"));
		} else if (rootMenuCode.equals("-1")) {
			criteria.add(Restrictions.isNull("parent"));
			criteria.add(Restrictions.eq("priority", 0));
		} else {
			criteria.add(Restrictions.eq("parent.id", rootMenuCode));
		}

		criteria.addOrder(Order.asc("priority"));
		Set<SysResources> rsets = this.getCurrAdmin(request).getRole().getResources();
		List<SysResources> list = criteria.list();
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();

		for (SysResources temp : list) {
			if (rsets.contains(temp)) {
				mapList.add(getMapObj(temp));
			}
		}

		String listJson = JSONSerializer.toJSON(mapList).toString();
		writerTo(response, listJson);
	}

	/**
	 * 把资源 对象封装成菜单对象
	 * 
	 * @param source
	 * @return
	 */
	private static Map<String, Object> getMapObj(SysResources source) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", source.getId());
		map.put("text", source.getRsName());
		map.put("leaf", source.getLeaf());
		map.put("rsCustomMark", source.getRsCustomMark());
		map.put("functionName", source.getRsFunctionName());
		map.put("rsFunctionJsPath", source.getRsFunctionJsPath());
		return map;
	}

}
